﻿using SF.API.Payment.wxpay;
using SF.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.TenPayLibV3;
using SF.Ucenter.api.wxpay;
using System.Collections;
using System.Configuration;
using System.IO;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Web.SessionState;


namespace SF.Ucenter.api.wxpay
{
    /// <summary>
    /// 单例模式 处理订单
    /// </summary>
    public class wxOrderTmpMgr : IRequiresSessionState
    {
        static wxOrderTmpMgr uniCounter;
        private int totNum = 0;
        private wxOrderTmpMgr()
        {
            Thread.Sleep(400); //假设多线程的时候因某种原因阻塞400毫秒 
        }
        [MethodImpl(MethodImplOptions.Synchronized)] //方法的同步属性 
        static public wxOrderTmpMgr instance()
        {
            if (null == uniCounter)
            {
                uniCounter = new wxOrderTmpMgr();
            }
            return uniCounter;
        }


        /// <summary>
        /// 【微支付】 订单付款成功，处理订单：1将订单的状态改成付款完成；
        /// 
        /// </summary>
        /// <param name="beforeFunName"></param>
        /// <param name="out_trade_no">商户订单号</param>
        /// <param name="transaction_id">订单交易号</param>
        /// <param name="pay_info">支付结果</param>
        /// <param name="total_fee">付款金额（单位为分）</param>
        /// <param name="otid">订单临时表id</param>
        /// <returns>有错误则返回错误信息，正确，则返回空字符串</returns>
        public string ProcessPaySuccess_wx(string beforeFunName, string out_trade_no, string transaction_id, string pay_info, int total_fee)
        {           
            total_fee = total_fee / 100;       
          
            try
            {
                BLL.sf_goods_order bll = new BLL.sf_goods_order();
                Model.sf_user_info users = System.Web.HttpContext.Current.Session[SF.Common.DTKeys.SESSION_ADMIN_INFO] as Model.sf_user_info;
                WriteTxt("修改支付后的回调：users：" + users + "，busnieseNum：" + users.busnieseNum + "，字符条件：" + Utils.getWhereByInfo(users.busnieseNum, users.appNum, users.templatesNum));
                //获取 订单 对象
                Model.sf_goods_order orderInfo = bll.GetModel("orderNum='" + out_trade_no + "' and " + Utils.getWhereByInfo(users.busnieseNum, users.appNum, users.templatesNum));
                //判断是否掉单
                if (orderInfo.isPay!=2)
                {
                    orderInfo.payTime = DateTime.Now;
                    orderInfo.isPay = 2;
                    if (bll.Update(orderInfo))
                    {
                        WriteTxt("已修改订单状态，准备处理库存！");
                        //获取商品对象
                        BLL.sf_goods_orderdetal detalBll = new BLL.sf_goods_orderdetal();
                        List<Model.sf_goods_orderdetal> orders = detalBll.GetModelList("orderNum='" + orderInfo.orderNum + "' and " + Utils.getWhereByInfo(users.busnieseNum, users.appNum, users.templatesNum));
                        BLL.sf_goods_amounts amountBll = new BLL.sf_goods_amounts();
                        //订单中第几个商品错误
                        int error = 0;
                        //遍历 商品 变更其库存
                        for (int i = 0; i < orders.Count; i++)
                        {
                            Model.sf_goods_amounts amount = amountBll.GetModel(Convert.ToInt64(orders[i].amountId));
                            if (amount!=null)
                            {
                                amount.amount -= Convert.ToInt64(orders[i].numbers);
                                if (!amountBll.Update(amount))
                                {
                                    error = i + 1;
                                    break;
                                }
                                WriteTxt("处理库存完成！");
                            }
                            else
                            {
                                BLL.sf_goods_info goodBll = new BLL.sf_goods_info();
                                Model.sf_goods_info good = goodBll.GetModel("goodsNum='" + orders[i].goodsNum + "' and " + Utils.getWhereByInfo(users.busnieseNum, users.appNum, users.templatesNum));
                                good.num -= Convert.ToInt32(orders[i].numbers);
                                if (!goodBll.Update(good))
                                {
                                    error = i + 1;
                                    break;
                                }
                                WriteTxt("处理库存完成！");
                            }
                        }
                        if (error == 0)
                        {
                            return "";
                        }
                        //else
                        //{
                        //    //商品库存  出现错误 还原商品
                        //    for (int i = 0; i < error - 1 & i < orders.Count; i++)
                        //    {
                        //        Model.goods_Amounts amount = amountBll.GetModel(Convert.ToInt64(orders[i].amountId));
                        //        amount.amount += Convert.ToInt64(orders[i].numbers);
                        //        amountBll.Update(amount);
                        //    }
                        //    return null;
                        //}
                    }
                    else{return null;}
                }
                else{return null;}
                return null;

            }
            catch (Exception ex)
            {
                WriteTxt("异常：" + ex.Message);
                return null;
            }

        }


        public void Inc() { totNum++; }
        public int GetCounter() { return totNum; }


        /// <summary>
        /// 记录bug，以便调试
        /// </summary>
        /// 
        /// <returns></returns>
        public bool WriteTxt(string str)
        {
            try
            {
                FileStream fs = new FileStream(Utils.GetMapPath("bugLog.txt"), FileMode.Append);
                StreamWriter sw = new StreamWriter(fs);
                //开始写入
                sw.WriteLine(str);
                //清空缓冲区
                sw.Flush();
                //关闭流
                sw.Close();
                fs.Close();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 设当前页完整地址 
        /// 比如：http://www.jb51.net/aaa/bbb.aspx?id=5&name=kelli 
        /// </summary>
        /// <returns></returns>
        public static string getTotalUrl()
        {
            string url = HttpContext.Current.Request.Url.ToString();
            return url;

        }
        /// <summary>
        /// url请求里的参数
        /// 过滤非法字符
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string QueryString(string param)
        {
            if (HttpContext.Current.Request[param] == null || HttpContext.Current.Request[param].ToString().Trim() == "")
            {
                return "";
            }
            string ret = HttpContext.Current.Request[param].ToString().Trim();
            ret = ret.Replace(",", "");
            ret = ret.Replace("'", "");
            ret = ret.Replace(";", "");

            return ret;
        }

    }
}